package com.laoma.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.laoma.gateway.common.CommonResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

@Configuration
public class GatewayConfig {

//    @Bean
//    public RouteLocator getRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {
//        RouteLocator routeLocator = routeLocatorBuilder.routes()
//                .route("order-center", r -> r.path("/ordercenter/**").uri("http://localhost:8000/"))
//                .route("user-center", r -> r.path("/usercenter/**").uri("http://localhost:8001/"))
//                .build();
//        return routeLocator;
//    }
    @PostConstruct
    public void init() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse>  handleRequest(ServerWebExchange exchange, Throwable throwable) {
                return ServerResponse.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .bodyValue(JSON.toJSONString(CommonResponse.buildFailCommonResponse("服务器繁忙，请稍后再试！")));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}
